import * as dotenv from 'dotenv'

dotenv.config({
  silent: true
})

class MissingConfigError extends Error {
 constructor(key) {
   super(`Missong env param ${key}`)
 }
}

// declare config class
class Config {
  port: number
  admin_host: string
  constructor() {
    this.port = Number(this.isOptional('PORT') || 3000)
    this.admin_host = this.isMandatory('ADMIN_HOST')
  }
  isOptional(key) {
    if (typeof(process.env[key]) === 'undefined' || process.env[key].length === 0) {
      console.warn(`${key} missing, falling back to defaults --- some features may not work.`)
      return null
    } else {
      return process.env[key]
    }
  }
  isMandatory(key) {
    if (typeof(process.env[key]) === 'undefined' || process.env[key].length === 0) {
      throw new MissingConfigError(key)
    }
    return process.env[key]
  }
}

export default new Config()
